package daoIpmt;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import beans.Follow;
import beans.Likes;
import dao.FollowDao;
import utils.DataSourceUtils;

public class FollowDaoIpmt implements FollowDao {
	QueryRunner qu = new QueryRunner(DataSourceUtils.getDataSource());

	@Override
	public void addFollow(Follow follow) {

		String sql1 = "select * from follow where username = ? and followusername=?";
		Follow follow2;
		try {
			follow2 = qu.query(sql1, new BeanHandler<Follow>(Follow.class), follow.getUsername(),
					follow.getFollowusername());
			if (follow2 == null) {
				follow.setStatus(1);
				String sql2 = "insert into follow values(?,?,?)";
				qu.update(sql2, follow.getUsername(), follow.getFollowusername(), follow.getStatus());
			} else {
				if (follow.getStatus() == 1) {
					String sql4 = "update follow set status=? where username=? and followusername=?";
					follow.setStatus(0);
					qu.update(sql4, follow.getStatus(), follow.getUsername(), follow.getFollowusername());
				} else {
					String sql3 = "update follow set status=? where username=? and followusername=?";
					follow.setStatus(1);
					qu.update(sql3, follow.getStatus(), follow.getUsername(), follow.getFollowusername());
				}
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	@Override
	public void getStatus(Follow follow) {
		String sql = "select * from follow where username = ? and likeusername=?";
		try {
			Follow follow2 = qu.query(sql, new BeanHandler<Follow>(Follow.class), follow.getUsername(),
					follow.getFollowusername());
			if (follow2 != null) {
				follow.setStatus(follow2.getStatus());
			} else {
				follow.setStatus(0);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<Follow> getfollowUsername(String username) {
		String sql = "select * from follow where username = ?";
				try {
					List<Follow> list = qu.query(sql, new BeanListHandler<Follow>(Follow.class), username);
					return list;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
		
	}

}
